package amani.wechat.platform.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.req.model.message.TemplateData;
import org.jeewx.api.core.req.model.message.TemplateMessage;
import org.jeewx.api.core.util.HttpRequestProxy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import amani.wechat.platform.controller.model.AddCardReturnData;
import amani.wechat.platform.controller.model.CommitOrdersReturnData;
import amani.wechat.platform.services.ICommonService;
import amani.wechat.platform.services.IOrdersService;
import amani.wechat.platform.services.model.HotProduct;
import amani.wechat.platform.services.model.Staffinfo;
import amani.wechat.platform.utils.WxUtils;

/**
 *  VIP预约 
 *  
 * @author VV
 *
 */
@Controller
@RequestMapping("/Orders")
public class OrdersController {
	
	@Resource(name="OrdersService")
	IOrdersService ordersService ;
	
	@Resource(name="CommonService")
	ICommonService commonService ;
	

	private static Logger logger = Logger.getLogger(OrdersController.class);
	
	@RequestMapping("/Success")
	public String success(String cardId,String cardCode,String status,String orderNo ,String staffno,String orderDate,String ordersProject ,Model model,HttpServletRequest request) throws WexinReqException { 
		JSONObject codeExt=null;
		if(cardCode!=null){
			codeExt=JSONObject.fromObject(cardCode);
		}
		if(status.equals("20")){
			commonService.updtaeCardCodeState(codeExt.getString("code"), 2);
		}
		model.addAttribute("status", status);
		model.addAttribute("cardCode",codeExt==null?"": codeExt.getString("code"));
		model.addAttribute("cardId", cardId);
		
		if( orderNo!=null||orderDate!=null){
			// 向会员用户发送预约消息通知 
			String openid = (String) request.getSession().getAttribute("openid");
			String first = "您好，您的预约已被登记。";
			String keyword1 = orderDate;
			String keyword2 = ordersProject;
			amani.wechat.platform.services.model.Staffinfo staff = commonService.loadStaffInfo(staffno);
			String keyword3 = staff.getStaffname();
			String keyword4 = staff.getCompname();
			String keyword5 = codeExt==null?"":"券号："+ codeExt.getString("code");
			String remark = "感谢您的光临"; 
			this.Ssvcr("YgjT5DR8bYfLmfg5KQVwOce2u3k28c10zKByrk59Zik", first, keyword1, keyword2, keyword3, keyword4, keyword5, remark, openid);
			// 向员工发送预约消息通知
			openid = (String) request.getSession().getAttribute("openid");
			first = "有新的客户预约，请及时确认";
			keyword1 = "微信端客户";
			keyword2 = "微信联系";
			keyword3 = orderDate;
			keyword4 = ordersProject;
			keyword5 = "";
			remark = codeExt==null?"":"券号："+ codeExt.getString("code"); 
			this.Ssvcr("wwi_yFjxmV_ux6d0i50eL8G1lQ5JQ-9gk4GbaU2I4uI", first, keyword1, keyword2, keyword3, keyword4, keyword5, remark, openid);
			
		}
		return "orders/success"; 
	}
	
	@RequestMapping("/mf/Success")
	public String mf_success(String cardId,String cardCode,String status,String orderNo ,String staffno,String orderDate,String ordersProject ,Model model,HttpServletRequest request) throws WexinReqException { 
		JSONObject codeExt=null;
		if(cardCode!=null){
			codeExt=JSONObject.fromObject(cardCode);
		}
		if(status.equals("20")){
			commonService.updtaeCardCodeState(codeExt.getString("code"), 2);
		}
		model.addAttribute("status", status);
		model.addAttribute("cardCode",codeExt==null?"": codeExt.getString("code"));
		model.addAttribute("cardId", cardId);
		
		if( orderNo!=null||orderDate!=null){
			// 向会员用户发送预约消息通知 
			String openid = (String) request.getSession().getAttribute("openid");
			String first = "您好，您的预约已被登记。";
			String keyword1 = orderDate;
			String keyword2 = ordersProject;
			amani.wechat.platform.services.model.Staffinfo staff = commonService.loadStaffInfo(staffno);
			String keyword3 = staff.getStaffname();
			String keyword4 = staff.getCompname();
			String keyword5 = codeExt==null?"":"券号："+ codeExt.getString("code");
			String remark = "感谢您的光临"; 
			this.Ssvcr("YgjT5DR8bYfLmfg5KQVwOce2u3k28c10zKByrk59Zik", first, keyword1, keyword2, keyword3, keyword4, keyword5, remark, openid);
			// 向员工发送预约消息通知
			openid = (String) request.getSession().getAttribute("openid");
			first = "有新的客户预约，请及时确认";
			keyword1 = "微信端客户";
			keyword2 = "微信联系";
			keyword3 = orderDate;
			keyword4 = ordersProject;
			keyword5 = "";
			remark = codeExt==null?"":"券号："+ codeExt.getString("code"); 
			this.Ssvcr("wwi_yFjxmV_ux6d0i50eL8G1lQ5JQ-9gk4GbaU2I4uI", first, keyword1, keyword2, keyword3, keyword4, keyword5, remark, openid);
			
		}
		return "orders/mf/success"; 
	}
	
	/**
	 * 选择服务类型
	 * @param model
	 * @return
	 */
	@RequestMapping("/Step1")
	public String step1( Model model) {
		List<HotProduct> products= ordersService.getHotProduct();
		model.addAttribute("HotProducnts", products);
		return "orders/step1";
	}
	
	/**
	 * 选择发型师
	 * @param model
	 * @return
	 */
	@RequestMapping("/Step2")
	public String step2(String sourceType,
			String ordersFactProject,
			String price,
			String cardid,
			String projectno,
			String projectname,
			String xcoordinate,
			String ycoordinate,
			HttpServletRequest  request,
			Model model) { 
		model.addAttribute("ordersFactProject", ordersFactProject);
		String opendid=(String)request.getSession().getAttribute("openid");
		List<Staffinfo> staffinfos= ordersService.getConsumedStaffinfos(opendid,ordersFactProject);
		model.addAttribute("ServicedStaffinfos", staffinfos); 
		List<Staffinfo> nearstaffinfos= ordersService.getNearStaffinfos(ordersFactProject, xcoordinate, ycoordinate);  
		model.addAttribute("NearStaffinfos", nearstaffinfos); 
		model.addAttribute("ycoordinate", ycoordinate); 
		model.addAttribute("xcoordinate", xcoordinate); 	
		if(price!=null){
			model.addAttribute("price", Double.parseDouble( price)); 
		}else {
			model.addAttribute("price",0);
		}
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname); 
		model.addAttribute("sourceType", sourceType); 
		return "orders/step2";
	}
	
	
	/**
	 * 选择发型师
	 * @param model
	 * @return
	 */
	@RequestMapping("/mf/Step2")
	public String mf_step2(String sourceType,
			String ordersFactProject,
			String price,
			String cardid,
			String projectno,
			String projectname,
			String xcoordinate,
			String ycoordinate,
			HttpServletRequest  request,
			Model model) { 
		model.addAttribute("ordersFactProject", ordersFactProject);
		String opendid=(String)request.getSession().getAttribute("openid");
		List<Staffinfo> staffinfos= ordersService.getConsumedStaffinfos(opendid,ordersFactProject);
		model.addAttribute("ServicedStaffinfos", staffinfos); 
		List<Staffinfo> nearstaffinfos= ordersService.getNearStaffinfos(ordersFactProject, xcoordinate, ycoordinate);  
		model.addAttribute("NearStaffinfos", nearstaffinfos); 
		model.addAttribute("ycoordinate", ycoordinate); 
		model.addAttribute("xcoordinate", xcoordinate); 	
		if(price!=null){
			model.addAttribute("price", Double.parseDouble( price)); 
		}else {
			model.addAttribute("price",0);
		}
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname); 
		model.addAttribute("sourceType", sourceType); 
		return "orders/mf/step2";
	}
	/**
	 * 选择服务时间
	 * @param openid 客户id
	 * @param staffno 员工编号 
	 * @param model 页面数据模型
	 * @return
	 */
	@RequestMapping("/Step3")
	public String step3(String staffno ,
			String xcoordinate,
			String ycoordinate,
			String ordersFactProject,
			String companyno,
			String sourceType, 
			String price,
			String cardid,
			String projectno,
			String projectname,
			Model model) { 
		model.addAttribute("ordersFactProject", ordersFactProject); 
	    model.addAttribute("staffno",staffno);   
		model.addAttribute("price",Double.parseDouble( price)); 
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname);  
	    model.addAttribute("companyno",companyno);
		return "orders/step3";
	}
	
	/**
	 * 选择服务时间
	 * @param openid 客户id
	 * @param staffno 员工编号 
	 * @param model 页面数据模型
	 * @return
	 */
	@RequestMapping("/mf/step3")
	public String mf_step3(String staffno ,
			String xcoordinate,
			String ycoordinate,
			String ordersFactProject,
			String companyno,
			String sourceType, 
			String price,
			String cardid,
			String projectno,
			String projectname,
			Model model) { 
		model.addAttribute("ordersFactProject", ordersFactProject); 
	    model.addAttribute("staffno",staffno);   
		model.addAttribute("price",Double.parseDouble( price)); 
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname);  
	    model.addAttribute("companyno",companyno);
		return "orders/mf/step3";
	}
	
	/**
	 * 确认提交信息
	 * 
	 * @param openid
	 * @param staffno
	 * @param model
	 * @return
	 * @throws WexinReqException 
	 */
	@RequestMapping("/Step4")
	public String step4(String openid,
			String staffno,
			String orderDate,
			String xcoordinate,
			String ycoordinate,
			String ordersFactProject, 
			String companyno,
			String sourceType, 
			String price,
			String cardid,
			String projectno,
			String projectname,
			Model model) throws WexinReqException { 
		model.addAttribute("ordersFactProject", ordersFactProject);
	    model.addAttribute("openid",openid);
	    List<Map<String, Object>> meList= commonService.loadMemberinfoByOpenid(openid);
	    Map<String, Object> memeberInfo=null;
	    if(meList.size()>0){
	    	memeberInfo=meList.get(0);
	    	model.addAttribute("cardno",(String)memeberInfo.get("cardno"));
	    }
	      
	    List<Staffinfo> staffinfos= ordersService.getConsumedStaffinfos(openid,ordersFactProject);
	    Staffinfo staffinfo= null;//commonService.loadStaffInfo(staffno);
	    for (int i = 0; i < staffinfos.size(); i++) {
			if(staffinfos.get(i).getStaffno()==staffno){
				staffinfo=staffinfos.get(i);
				break;
			}
		}
	    if(staffinfo==null){
	    	staffinfos= ordersService.getNearStaffinfos(ordersFactProject, xcoordinate, ycoordinate); 
		    for (int i = 0; i < staffinfos.size(); i++) {
				if(staffinfos.get(i).getStaffno().equals(staffno)){
					staffinfo=staffinfos.get(i);
					break;
				}
			}

	    }
	    if(staffno!=null){
	    	staffinfo= commonService.loadStaffInfo(staffno);
	    }
	    model.addAttribute("staff",staffinfo);  
	    model.addAttribute("orderDate",orderDate);  
	    model.addAttribute("companyno",companyno);  
	    model.addAttribute("compname",staffinfo.getCompname()); 
	    
	    model.addAttribute("price", price); 
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname);  
		
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderid =  sFormat.format(new Date())+ _random.nextInt(1000);

		model.addAttribute("orderid", orderid);  
		
		
	    return "orders/step4"; 
	}
	
	
	@RequestMapping("/mf/step4")
	public String mf_step4(String openid,
			String staffno,
			String orderDate,
			String xcoordinate,
			String ycoordinate,
			String ordersFactProject, 
			String companyno,
			String sourceType, 
			String price,
			String cardid,
			String projectno,
			String projectname,
			Model model) throws WexinReqException { 
		model.addAttribute("ordersFactProject", ordersFactProject);
	    model.addAttribute("openid",openid);
	    List<Map<String, Object>> meList= commonService.loadMemberinfoByOpenid(openid);
	    Map<String, Object> memeberInfo=null;
	    if(meList.size()>0){
	    	memeberInfo=meList.get(0);
	    	model.addAttribute("cardno",(String)memeberInfo.get("cardno"));
	    }
	      
	    Staffinfo staffinfo= commonService.loadStaffInfo(staffno);
	    model.addAttribute("staff",staffinfo);  
	    model.addAttribute("orderDate",orderDate);  
	    model.addAttribute("companyno",companyno);  
	    model.addAttribute("compname",staffinfo.getCompname()); 
	    
	    model.addAttribute("price", price); 
		model.addAttribute("sourceType", sourceType); 
		model.addAttribute("cardid", cardid); 
		model.addAttribute("projectno", projectno); 
		model.addAttribute("projectname", projectname);  
		
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderid =  sFormat.format(new Date())+ _random.nextInt(1000);

		model.addAttribute("orderid", orderid);  
		
		
	    return "orders/mf/step4"; 
	}
	
	private static Random _random = new Random();
	/**
	 * 保存提交预约数据
	 * @param openid
	 * @param staffno
	 * @param orderDate
	 * @param ordersFactProjectl
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/CommitOrder")
	@ResponseBody
	public CommitOrdersReturnData commitOrders(
			String cardno,
			String mobile,
			String projectno,
			String projectname,
			String orderDate,
			String compid,
			String compname,
			String staffno,
			String manageno,
			String staffname,
			String orderid,
			int ispz,
			
			String sourceType, 
			String price,
			String cardid,HttpServletRequest request
			) throws Exception {   
		CommitOrdersReturnData requestStatus=new CommitOrdersReturnData();
		try{
		//SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		//String orderid =  sFormat.format(new Date())+ _random.nextInt(1000);
			String orderString=  commonService.loadOrderById(orderid);
			net.sf.json.JSONArray jsonarray = net.sf.json.JSONArray
					.fromObject(orderString);
			if(jsonarray.size()>0&&!((JSONObject)jsonarray.get(0)).get("ordersid").equals("")){
				CommitOrdersReturnData returnData=new CommitOrdersReturnData();
				returnData.setIsSuccessed(false);
				return returnData;  
			}
			
			SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMdd");
			Date dateTimeDate=new Date(Long.parseLong(orderDate)); 
			String date = sFormat.format(dateTimeDate);//strtotime($opentime);
			sFormat = new SimpleDateFormat("HHmmss");
			String times=sFormat.format(dateTimeDate);
			//double price=0;
			   
			requestStatus.setIsSuccessed(true);
			//返回信息为Json数据，包含订单字段：staffno，staffname，staffopenid，manageno
	
			String opendid = (String) request.getSession().getAttribute("openid");
			String saveState= commonService.saveNewOrders(compid, orderid, projectno,
					 staffno, ispz, date, 
					 times, mobile, cardno,
					 opendid, staffname); 
			if("3".equals(saveState)){
				requestStatus.setIsSuccessed(false);
				requestStatus.setExceptionCode("此时间段已被预约。");
				return requestStatus;
			}
			if(!sourceType.equals("Orders")){
				String clientIP=(String)request.getSession().getAttribute("clientIp");
			    //生成支付数据 
				double price1 = Double.parseDouble(price);
				JSONObject payJsonData=WxUtils.GeneratePayJosn(orderid,opendid,orderid,price1,clientIP);
				requestStatus.setPayJsonData(payJsonData);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return requestStatus;
	} 
	
	private String Ssvcr(String templateID,String first,String keyword1,String keyword2,String keyword3,String keyword4,String keyword5 ,String remark,String openid){
		String result = "true";
		try {
			if(templateID==null){
				result = "error:templateID is null";
			}else if(openid==null){
				result = "error:openid is null";
			}
			String accessToken = WxUtils.GetAccessToken();
			JSONObject obj=new JSONObject();
			//
			obj.put("touser", openid);
			obj.put("template_id", templateID);
			obj.put("topcolor", "#FF0000");

			TemplateMessage data = new TemplateMessage();
			//first
			TemplateData firstT = new TemplateData();
			firstT.setColor("#173177");
			firstT.setValue(first);
			data.setFirst(firstT);

			//keyword1
			TemplateData keynote1 = new TemplateData();
			keynote1.setColor("#173177");
			keynote1.setValue(keyword1);
			data.setKeyword1(keynote1);

			//keyword2
			TemplateData keynote2 = new TemplateData();
			keynote2.setColor("#173177");
			keynote2.setValue(keyword2);
			data.setKeyword2(keynote2); 
			
			//keyword3
			TemplateData keynote3 = new TemplateData();
			keynote3.setColor("#173177");
			keynote3.setValue(keyword3);
			data.setKeyword3(keynote3);
			
			//keyword4
			TemplateData keynote4 = new TemplateData();
			keynote4.setColor("#173177");
			keynote4.setValue(keyword4);
			data.setKeyword4(keynote4);
			
			//keyword5
			TemplateData keynote5 = new TemplateData();
			keynote5.setColor("#173177");
			keynote5.setValue(keyword5);
			data.setKeyword5(keynote5);

			//remark
			TemplateData remarkT = new TemplateData();
			remarkT.setColor("#173177");
			remarkT.setValue(remark);
			data.setRemark(remarkT);
			
			obj.put("data",data);
			String reqUrl=String.format(
					"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",
					WxUtils.GetAccessToken());
			Map parameters=new HashMap();
			String jsonResultStr = HttpRequestProxy.doJsonPost(reqUrl, parameters,obj.toString());
		} catch (WexinReqException e) {
			result = e.getMessage();
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping("/SendCard") 
	@ResponseBody 
	public AddCardReturnData SendCard(String compid,String cardId,String orderNo,float cardfaceamt, String orderDate ,String staffNo,HttpServletRequest request) throws WexinReqException {
		AddCardReturnData result=new AddCardReturnData();
		result.setCardId(cardId); 
		String openid=(String)request.getSession().getAttribute("openid");
		String cardCode = getCode();
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMdd");
		Date dateTimeDate=new Date(); 
		String enabledate = sFormat.format(dateTimeDate);
		String oldvalidate = orderDate.split(" ")[0].replace("-", "");
		String lastvalidate = oldvalidate;
		String ineritemno = "321";
		amani.wechat.platform.services.model.Staffinfo staffinfo = commonService.loadStaffInfo(staffNo);
		ineritemno = getIneritemno(staffinfo);
		int i = 0;
		boolean flag = true;
		while(!commonService.saveNointernalcardinfo(compid, cardCode, 1, cardfaceamt, 1, 2, 1, "", "", oldvalidate, lastvalidate, enabledate, 0, "", 0, 0,openid)){
			cardCode = getCode();
			i++;
			if(i>10){
				flag = false;
				break;
			}
		}
		if(flag){
			commonService.saveDnointernalcardinfo(compid, cardCode, 1, ineritemno, 0, 0, cardfaceamt, 0, 0, 1, "", "");
		}
		commonService.updtaeOrderCard(orderNo, cardId, cardCode);
		result.setCardExt(WxUtils.getCardExt(cardId,cardCode, openid));  
		return result;
		
	}
	private String getIneritemno(Staffinfo staffinfo) {
		String res = "321";
		if(staffinfo!=null&&staffinfo.getPosition()!=null){
			switch (staffinfo.getPosition()){
				case "003":
					res = "321";break;
				case "006":
					res = "322";break;
				case "007":
					res = "323";break;
				case "00701":
					res = "324";break;
				default:
					res = "321";break;
			}
			
		}
		return res;
	}

	public String getCode() {
		String code = new Date().getTime()+"";
		int j = _random.nextInt(10000);
		while(j<1000){
			j = _random.nextInt(10000);
		}
		code = j+code.substring(5);
		return code;
	}
	
}
